// 路由模块
import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '@/views/Home.vue'
import Detail from '../views/Detail.vue'
import VuexTest from '../views/VuexTest'
import Cart from '../views/Cart'
import CheckOut from '../views/CheckOut'
import Login from '../views/Login'
import Main from '../views/Main'
import Account from '../views/Account'
import store from '../store/index'

Vue.use(VueRouter)
// let isLogin = false // 模拟登录状态
const router = new VueRouter({
  // mode:'history',  //上线打包后，需要后端配置做一个接口配置
  routes:[
    {
      path:'/login',
      component:Login
    },
    {
      path:'/reg',
      component:()=>import("../views/Reg.vue")
    },
    {
      path:'/',
      component:Main,
      children:[
        {
          path:'/',
          component:Home
        },
        {
          path:'detail/:id',
          component:Detail
        },
        {
          path:'cart',
          component:Cart
        },
        {
          path:'checkout',
          component:CheckOut
        },
        {
          path:'account',
          component:Account,
          // beforeEnter(to,from,next){
          //   if(isLogin){ //判断登录状态
          //     next()
          //   }else{
          //     next('/login')
          //   }
          // },
          children:[
            {
              path:'order',
              component:()=>import("../views/Account/Order.vue") //路由懒加载
            },
            {
              path:'address',
              component:()=>import("../views/Account/Address.vue") //路由懒加载
            },
            {
              path:'setting',
              component:()=>import("../views/Account/Setting.vue") //路由懒加载
            }
          ]
        },
        {
          path:'vuex/test',
          component:VuexTest
        }
      ]
    }
  ]
})

// 全局守卫

router.beforeEach((to,from,next)=>{
  console.log('全局路由守卫拦截',to,from);
  if(to.path.indexOf('/account')!=-1){
    if(store.state.user.userInfo){ //判断登录状态
      next()
    }else{
      // next('/login')
      next({
        path:'/login',
        query:{
          target:to.path //记录用户在跳转登录前，本来想去访问的路由
        }
      })
    }
    return
  }
  next() //访问没有限制的路由，直接放行
})
export default router